import backend
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
import MabiCommerce.raw
import MabiCommerce.pretty

# Create your views here.

out_formatters  = { '' : MabiCommerce.pretty.render, 'json' : MabiCommerce.raw.render }

def from_server(request, server_name, town_name, mode=''):
    mode = mode.lower()
    if not mode in out_formatters:
        mode = ''
    #end if
    try:
        items = backend.from_server(server_name, town_name)
    except ObjectDoesNotExist as e:
        return HttpResponse("ERROR: %s" % (e.args), status=409)
    #end try
    return out_formatters[mode](server_name, town_name, items[0], items[1])
#end def

def from_IP(request, ip, port, town_name, mode=''):
    mode = mode.lower()
    if not mode in out_formatters:
        mode = ''
    #end if
    try:
        items, server_name = backend.from_IP(ip, port, town_name)
    except ObjectDoesNotExist as e:
        return HttpResponse("ERROR: %s" % (e.args), status=409)
    #end try
    return out_formatters[mode](server_name, town_name, items[0], items[1])
#end def

in_formatters = {'json' : MabiCommerce.raw.get_items}

@csrf_exempt
def to_server(request, server_name, town_name, mode='json'):
    if request.method != "POST":
        return HttpResponse('%s requests are not allowed' % request.method, status=405)
    #end if
    if not mode in in_formatters:
        mode = 'json'
    #end if
    try:
        item_profits = in_formatters[mode](request.raw_post_data)
        errors = backend.to_server(server_name, town_name, item_profits)
        if errors != '':
            raise Exception(errors)
        #end if
    except Exception as e:
        return HttpResponse("The following errors occured while processing your data:\r\n%s" % (e.args), status=409)
    #end try
    return HttpResponse('OK', status=200)
#end def

@csrf_exempt
def to_IP(request, ip, port, town_name, mode='json'):
    server_name = backend.get_server_name(ip, port)
    return to_server(request, server_name, town_name, mode)
#end def

# def server(request, server_name, town_name):
    # s = Server.objects.get(name=server_name)
    # t = Town.objects.get(name=town_name, server=s)
    # out = ', '.join([p.__unicode__() for p in Item.objects.filter(town=t)])
    # return HttpResponse(out)
# def IP(request, ip, port, town):
    # return HttpResponse('Wut?')